package br.com.pd.invocation;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import com.thoughtworks.xstream.XStream;

import br.com.pd.messaging.MessageIF;
import br.com.pd.messaging.ConsumerRequestHandle;
import br.com.pd.messaging.bean.Product;
import br.com.pd.messaging.bean.Supplier;
import br.com.util.PropertiesLoader;


public class SupplyInvoker extends Thread implements InvokerIF{
	
	private MarshallIF marshall;
	private List<MessageIF> messages;
	private ConsumerRequestHandle supplyHandle;
	private int checkerPeriod ;
	private boolean a;
	
	private List list;
	
	public SupplyInvoker(ConsumerRequestHandle s){
		this.a = false;
		this.supplyHandle = s;
		this.marshall = new Marshaller();
		this.messages = new ArrayList<MessageIF>();
		this.checkerPeriod = Integer.parseInt(PropertiesLoader.getInstance().getPropertie(PropertiesLoader.MESSAGE_CHECKER_PERIOD));
		loadDatabase(PropertiesLoader.getInstance().getPropertie(PropertiesLoader.CONSUMER_DATABASE));
		this.start();
	}
	
	private void loadDatabase(String propertie) {
		XStream x = new XStream();
		try {
			this.list = (List) x.fromXML(new FileInputStream(propertie));
			System.out.println("banco carregado " + this.list.size());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	@Override
	// decodificar com o marshall 
	// enviar a mensagem de volta
	public void execute(String m) {
		this.a = true;
		MessageIF message = marshall.unMarshall(m);
		System.out.println("operation " + message.getOperation() );
		if (message.getOperation().equals(MessageIF.SUBSCRIBE)) {
			System.out.println("Debug: Invoker Supply  : " + message.getResponse());
			
		}else if(message.getOperation().equals(MessageIF.SUPPLY)){
			List<Object> p = message.getParams();
			Supplier s = new Supplier();
			for (int i = 0; i < p.size(); i++) {
				Product tmp = (Product) p.get(i);
				for (int j = 0; j < list.size(); j++) {
					if (tmp.getCode().equals(((Product)list.get(j)).getCode())) {
						s.addProduct((Product)list.get(j));
					}	
				}
			}
			message.addResponse(s);
			this.messages.add(message);
		}
	}
	
	@Override
	public void run(){
		while(true){
			try {
				this.verifyReturnMessages();
				this.sleep(checkerPeriod);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	private void verifyReturnMessages(){
		List<MessageIF> tmp = new ArrayList<MessageIF>();
		for (MessageIF i : this.messages) {
			tmp.add(i);
		}
		for (MessageIF i : tmp) {
			this.messages.remove(i);
			String m = this.marshall.marshall(i);
			this.supplyHandle.send(m, i.getFrom(), i.getPortSender());
		}
	}
	
	


}
